package api

import (
	"context"
	"net/http"
	"sdc/repository/db/dao"
	"sdc/repository/db/model"
	"sdc/service"
	"strconv"

	"github.com/gin-gonic/gin"
)

// Register 用户注册 用户传入用户名、密码、手机号、验证码，用户需要获取验证码
func Register(c *gin.Context) {
	var req struct {
		Username   string `json:"username" binding:"required,min=3,max=32"`
		Password   string `json:"password" binding:"required,min=6,max=32"`
		Phone      string `json:"phone" binding:"required,len=11"`
		VerifyCode string `json:"verify_code" binding:"required,len=6"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
			"data": err.Error(),
		})
		return
	}

	// 验证码校验

	// 注册用户，之后需要做用户名和密码校验和密码加密现在先简单处理
	user := &model.User{
		Username: req.Username,
		Phone:    req.Phone,
	}
	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewUserService(db)
	if err := service.Register(user, req.Password); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "注册失败",
			"data": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
}

// Login 用户登录
func Login(c *gin.Context) {
	var req struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewUserService(db)
	token, err := service.Login(req.Username, req.Password)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": 401,
			"msg":  "登录失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": gin.H{
			"token": token,
		},
	})
}

// GetUserInfo 获取用户信息
func GetUserInfo(c *gin.Context) {
	userID := c.GetUint64("user_id")

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewUserService(db)
	user, err := service.GetUserByID(userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "获取用户信息失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": user,
	})
}

// UpdateUserInfo 更新用户信息
func UpdateUserInfo(c *gin.Context) {
	userID := c.GetUint64("user_id")

	var req struct {
		Avatar   string `json:"avatar"`
		Nickname string `json:"nickname" binding:"required"`
		Phone    string `json:"phone" binding:"required,len=11"`
		Email    string `json:"email" binding:"required,email"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	user := &model.User{
		ID:       userID,
		Avatar:   req.Avatar,
		Username: req.Nickname,
		Phone:    req.Phone,
		Email:    req.Email,
	}

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewUserService(db)
	if err := service.UpdateUser(user); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "更新失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "更新成功",
	})
}

// ListUsers 获取用户列表
func ListUsers(c *gin.Context) {
	keyword := c.DefaultQuery("keyword", "")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))

	db := dao.NewDBClient(context.Background())
	service := service.NewUserService(db)

	users, total, err := service.ListUsers(keyword, page, pageSize)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "获取用户列表失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": gin.H{
			"list":  users,
			"total": total,
			"page":  page,
			"size":  pageSize,
		},
	})
}

// SubmitVerification 提交实名认证,先不做
// func SubmitVerification(c *gin.Context) {
// 	userID := c.GetUint64("user_id")

// 	var req struct {
// 		RealName string   `json:"real_name" binding:"required"`
// 		IDCard   string   `json:"id_card" binding:"required,len=18"`
// 		Type     int8     `json:"type" binding:"required,oneof=1 2 3"`
// 		Files    []string `json:"files" binding:"required,min=1"`
// 	}

// 	if err := c.ShouldBindJSON(&req); err != nil {
// 		c.JSON(http.StatusBadRequest, gin.H{
// 			"code": 400,
// 			"msg":  "参数错误",
// 		})
// 		return
// 	}

// 	verification := &model.UserVerification{
// 		UserID:    userID,
// 		Type:      req.Type,
// 		Documents: model.JSON(req.Files),
// 		Status:    0, // 待审核
// 	}

// 	if err := service.SubmitVerification(verification, req.RealName, req.IDCard); err != nil {
// 		c.JSON(http.StatusInternalServerError, gin.H{
// 			"code": 500,
// 			"msg":  "提交失败",
// 		})
// 		return
// 	}

// 	c.JSON(http.StatusOK, gin.H{
// 		"code": 200,
// 		"msg":  "提交成功",
// 	})
// }
